package com.kehutong.common;

import java.util.ArrayList;
import java.util.List;

import org.coraframework.bean.Beans;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.orm.Entity;
import org.coraframework.orm.jdbc.Page;

public class JSONUtils {
	
	public static List<String> toList(JSONArray jsonArray) {
		List<String> list = new ArrayList<>(jsonArray.size());
		for (int i = 0; i < jsonArray.size(); i ++) {
			list.add(jsonArray.getString(i));
		}
		
		return list;
	}

	public static <T extends Entity> JSONArray toJSONArray(List<T> list, String... includes) {
		JSONArray array = new JSONArray();

		for (int i = 0; i < list.size(); i++) {
			JSONObject v = new JSONObject();
			Beans.from(list.get(i)).to(v).include(includes).copy();
		}

		return array;
	}
	
	public static <T extends Entity> List<JSONObject> toJSONList(List<T> list, String... includes) {
		List<JSONObject> array = new ArrayList<>();

		for (int i = 0; i < list.size(); i++) {
			JSONObject v = new JSONObject();
			Beans.from(list.get(i)).to(v).include(includes).copy();
		}

		return array;
	}
	
	public static <T extends Entity> Page<JSONObject> toPage(Page<T> list, String... includes) {
		Page<JSONObject> page = new Page<>();
		page.setCount(list.getCount());
		page.setPageCount(list.getPageCount());
		page.setPageNo(list.getPageNo());
		page.setPageSize(list.getPageSize());

		List<JSONObject> array = toJSONList(list.getList(), includes);
		page.setList(array);

		return page;
	}
}
